<template>
  <div class="map-container">
    <div class="map" :id="mapId"></div>
  </div>
</template>

<script>
import GPS from '@/utils/gps'

let markers = {};
export default {
  name: 'Map',
  data() {
    return {
      mapId: 'map' + new Date().getTime() + parseInt(Math.random() * 1000)
    };
  },

  mounted() {
    if (window.AMap) {
      this.initMap();
    } else {
      window.addEventListener('mapReady', this.initMap);
    }
  },
  beforeDestroy() {
    this.map && this.map.destroy();
    window.removeEventListener('mapReady', this.initMap);
  },
  methods: {
    initMap() {
      console.log('初始化地图：', this.map);
      if (this.map) return;
      // 动态添加属性，防止Vue监听
      this.map = new AMap.Map(this.mapId, {
        mapStyle: 'amap://styles/normal',
        viewMode: '2D', //是否为3D地图模式
        zoom: 14, //初始化地图级别
        center: [120.751001,30.76218] //初始化地图中心点位置
      });
      // 卫星地图切换
      this.map.addControl(new AMap.MapType());
    },
    createMarker(list, typeKey) {
        const clockIn = require('@/assets/images/clock-in.png')
        const clockOut = require('@/assets/images/clock-out.png')
        this.clearMapMarker(typeKey)
        if(list && list.length) {
            list.forEach(item => {
                item.lnglat = GPS.WGS84toGCJ02(item.longitude, item.latitude);
                const marker = new AMap.Marker({
                    position: item.lnglat,
                    icon: new AMap.Icon({
                        image: item.type==1?clockIn:clockOut,
                        size: [30,30],
                        imageSize: [30,30]
                    }),
                    offset: [-30, -30],
                    title: item.gmtReport,
                    label: {
                        direction: 'top',
                        content: `<div style="background:#fff;padding:8px;border-radius: 6px;font-weight:500;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);">${item.type==1?'上班：':'下班：'}${item.gmtReport}</div>`
                    },
                    extData: {...item}
                })
    
                markers[typeKey].push(marker)
            })
    
            this.map.add(markers[typeKey])
            // this.map.setFitView()
        }
    },
    clearMapMarker(typeKey) {
        if(typeKey) {
            this.map && markers[typeKey] && this.map.remove(markers[typeKey])
            markers[typeKey] = []
        }else{
            for(let k in markers) {
                this.map && markers[k] && this.map.remove(markers[k])
                markers[k] = []
            }
        }
        
    }
  }
};
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  .map {
    width: 100%;
    height: 100%;
    min-width: 20px;
    min-height: 20px;
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
}
</style>
